package com.etoak.controller;

import com.etoak.common.utils.DateUtils;
import com.etoak.common.utils.WordUtils;
import com.etoak.common.utils.uuid.IdUtils;
import com.etoak.entity.*;
import com.etoak.entity.dto.CheckListDto;
import com.etoak.entity.vo.CheckListVo;
import com.etoak.mapper.ChecklistMapper;
import com.etoak.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * checklist模块 Controller
 *
 * @author zhixuebin
 * @date 2022-05-12
 */
@RestController
@RequestMapping("/goertek/checklist")
public class CheckListController extends BaseController {

    @Autowired
    IChecklistService checklistService;

    @Autowired
    ITerritoryService territoryService;

    @Autowired
    IProductlineService productLineService;

    @Autowired
    IProductService productService;

    @Autowired
    IApplySituationService applySituationService;

    @Autowired
    ICheckListDraftService checkListDraftService;

    @Autowired
    ITypicalProblemService typicalProblemService;

    @Autowired
    IDesignGuideService designGuideService;

    @Autowired
    IUpdateReasonService updateReasonService;

    /**
     * 新增记录(提交)
     * @param checkList
     * @return
     */
    @Transactional
    @PostMapping("/add")
    public AjaxResult add(@RequestBody CheckList checkList){
        //设置主键
        String id = IdUtils.simpleUUID();
        checkList.setId(id);
        //设置应用场景
        String[] applicationScenarios = checkList.getApplicationScenariosList();
        if(!StringUtils.isNull(applicationScenarios)){
            List result = new ArrayList();
            for(int j = 0;j < applicationScenarios.length;j++){
                result.add(applicationScenarios[j]);
            }
            checkList.setApplicationScenarios(result.toString().replace("[","").replace("]",""));
        }
        //关联典型问题
        String[] typicalProblemList = checkList.getTypicalProblemList();
        if(!StringUtils.isNull(typicalProblemList)){
            List result = new ArrayList();
            for(int j = 0;j < typicalProblemList.length;j++){
                result.add(typicalProblemList[j]);

            }
            checkList.setAssociatedTypical(result.toString().replace("[","").replace("]",""));
        }
        //关联设计指导
        String[] designGuideList = checkList.getTypicalProblemList();
        if(!StringUtils.isNull(designGuideList)){
            List result = new ArrayList();
            for(int j = 0;j < designGuideList.length;j++){
                result.add(designGuideList[j]);

            }
            checkList.setAssociatedDesign(result.toString().replace("[","").replace("]",""));
        }

        int i = 0;
        /*判断当前操作类型*/
        /*String operationType = checkList.getOperationType();
        //如果当前为保存操作
        if(operationType.equals("0")){
            //状态设置为待提交
            checkList.setStatus(1);
        }else{
            //状态设置为待审核
            checkList.setStatus(2);
        }*/
        checkList.setDelStatus(0);
        checkList.setStatus(1);
        checkList.setCreateTime(DateUtils.getNowDate());

        i = checklistService.insertChecklist(checkList);

        //判断当前用户是否通过草稿新增记录,如是,添加成功后删除草稿
        //Draft draft = new Draft();
        //draft.setCreateBy(当前用户);
        //Draft search = checkListDraftService.getDraft(draft);
        //checkListDraftService.deleteDraft(search.getId);

        if(i > 0) {
            return AjaxResult.success("添加成功");
        }else {
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 查询知识列表
     * @param checkList
     * @return
     */
    @GetMapping("/getList")
    public PageInfo getList(@RequestParam(value = "pageNo",defaultValue = "1")Integer pageNo,
                                 @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                                 CheckList checkList){
        PageHelper.startPage(pageNo,pageSize);
        List<CheckList> list = checklistService.getList(checkList);
        PageInfo<CheckList> info = new PageInfo<>(list);
        return info;
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids){
        return toAjax(checklistService.deleteChecklist(ids));
    }

    /**
     * 逻辑删除
     * @param ids
     * @return
     */
    @GetMapping("/delete/{ids}")
    public AjaxResult remove2(@PathVariable String[] ids){
        int i = 0;
        for(String id : ids){
            CheckList list = checklistService.getChecklistItemById(id);
            list.setDelStatus(1);
            checklistService.updateChecklist(list);
            i++;
        }
        return AjaxResult.success("已删除"+ i +"条记录");
    }

    /**
     * 编辑修改
     * @param checklist
     * @return
     */
    @Transactional
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody CheckList checklist){
        //查询对应记录
        CheckList list = checklistService.getChecklistItemById(checklist.getId());
        //返回应用场景
        String[] applicationScenarios = checklist.getApplicationScenariosList();
        if(!StringUtils.isNull(applicationScenarios)){
            List result = new ArrayList();
            for(int j = 0;j < applicationScenarios.length;j++){
                result.add(applicationScenarios[j]);
            }
            checklist.setApplicationScenarios(result.toString().replace("[","").replace("]",""));
        }
        //返回典型问题
        String[] typicalProblemList = checklist.getTypicalProblemList();
        if(!StringUtils.isNull(typicalProblemList)){
            List result = new ArrayList();
            for(int j = 0;j < typicalProblemList.length;j++){
                result.add(typicalProblemList[j]);

            }
            checklist.setAssociatedTypical(result.toString().replace("[","").replace("]",""));
        }
        //关联设计指导
        String[] designGuideList = checklist.getTypicalProblemList();
        if(!StringUtils.isNull(designGuideList)){
            List result = new ArrayList();
            for(int j = 0;j < designGuideList.length;j++){
                result.add(designGuideList[j]);

            }
            checklist.setAssociatedDesign(result.toString().replace("[","").replace("]",""));
        }
        //添加修改原因
        ChecklistUpdateReason reason = new ChecklistUpdateReason();
        String id = IdUtils.simpleUUID();
        reason.setId(id);
        reason.setKnowledgeId(checklist.getId());
        reason.setUpdateReason(checklist.getUpdateReason());
        //reason.setCreateBy();
        reason.setCreateTime(DateUtils.getNowDate());
        int j = updateReasonService.add(reason);
        int i = 0;
        if (!StringUtils.isNull(list)) {
            i = checklistService.updateChecklist(checklist);
        }
        if(i > 0){
            return AjaxResult.success("修改成功");
        }else{
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 导出excel
     */
    //@GetMapping("/daochu")
    //public void daochu(HttpServletResponse response){
    //    InputStream fis;
    //    OutputStream fos;
    //    try {
    //        fis = new FileInputStream("C:\\Users\\Etoak\\Desktop\\解析文件测试1v.xlsx");
    //        response.setHeader("Content-Disposition" , "attachment;filename=" + new String("解析文件".getBytes(), "ISO8859-1") + ".xlsx" );
    //        fos = response.getOutputStream();
    //        byte[] data = new byte[5<<20];
    //        int len;
    //        while((len = fis.read(data))!=-1){
    //            fos.write(data,0,len);
    //        }
    //        fis.close();
    //        fos.close();
    //    }catch (Exception e){
    //        e.printStackTrace();
    //    }
    //}

    /**
     * 获取最新编码(根据所属领域生成)
     * @param code
     * @return
     */
    @GetMapping("/getNewCode")
    public AjaxResult getNewCode(@RequestParam String code){
        //返回map结果集
        Map resultMap = new HashMap();
        //获取当前知识所属领域
        DecimalFormat df = new DecimalFormat("00000000");
        //返回结果
        String result = "";
        String latestCode = "";
        //获取当前领域知识库中编码最大的一个
        List<CheckList> list = checklistService.getChecklistItemByTerritory(code);
        int num;
        //非空判断
        if(list.size() != 0 && list != null){
            //拿取编码最大的那个
            CheckList item = list.get(0);
            latestCode = item.getEncoding();
            num = Integer.parseInt(item.getEncoding().substring(item.getEncoding().indexOf(code) + 2));
            num++;
            String str = df.format(num);
            result = code + str;
        }else{
            //表中无数据,从一开始
            num = 1;
            String str = df.format(num);
            result = code + str;
        }
        resultMap.put("最新编码",result);
        resultMap.put("最近编码",latestCode);
        return AjaxResult.success(resultMap);
    }

    /**
     * 获取左侧树状结构
     * @return
     */
    /*@GetMapping("/getTree")
    public AjaxResult getTree(){
        List resultList = new ArrayList();
        List resultList2 = new ArrayList();
        //获取顶层菜单：领域
        List<Territory> territoryList = territoryService.getTerritory(new Territory());
        //获取领域对应的产品线
        for(Territory t : territoryList){
            List<ProductLine> productLineList = productLineService.getProductLineByTerritory(t.getId());
            checklistService.setChildren(t,productLineList,resultList);
            for(ProductLine line : productLineList){
                List<Product> productList = productService.getProductByProductLine(line.getId());
                checklistService.setChildren2(line,productList,resultList2);
            }
        }
        return AjaxResult.success(territoryList);
    }*/

    /**
     * 获取左侧树状结构
     * @return
     */
    /*@GetMapping("/getTrees")
    public AjaxResult getTrees(){
        List resultList = new ArrayList();
        List resultList2 = new ArrayList();
        List resultList3 = new ArrayList();
        //获取顶层菜单：领域
        List<Territory> territoryList = territoryService.getTerritory(new Territory());
        List<ProductLine> productLineList = productLineService.getProductLine(new ProductLine());
        List<Product> productList = productService.getProduct(new Product());
        for(Territory territory : territoryList){
            for(ProductLine productLine : productLineList){
                if(territory.getId().equals(productLine.getTerritoryId())){
                    for(Product product : productList){
                        if(productLine.getId().equals(product.getProductLineId())){
                            Map resultMap = new HashMap();
                            resultMap.put("id",product.getId());
                            resultMap.put("name",product.getProductName());
                            resultList3.add(resultMap);
                        }
                        Map resultMap2 = new HashMap();
                        resultMap2.put("id",productLine.getId());
                        resultMap2.put("name",productLine.getProductLineName());
                        resultMap2.put("children",resultList3);
                        resultList2.add(resultMap2);

                    }
                    Map resultMap3 = new HashMap();
                    resultMap3.put("id",territory.getId());
                    resultMap3.put("name",territory.getTerritoryName());
                    resultMap3.put("children",resultList2);
                    resultList.add(resultMap3);
                }
            }
        }
        return AjaxResult.success(resultList);
    }*/

    /**
     * 获取树状结构
     * @return
     */
    @RequestMapping("/getTrees")
    public List<Map<String,Object>> getTrees(){
        List<Map<String,Object>> territoryList = checklistService.query1();
        for(Map<String,Object> t: territoryList){
            List<Map<String,Object>> productLineList = checklistService.query2(t.get("id").toString());
            t.put("children", productLineList);
            for(Map<String,Object> p: productLineList){
                List<Map<String,Object>> productList = checklistService.query3(p.get("id").toString());
                p.put("children", productList);
            }
        }
        return  territoryList;
    }

    /**
     * 顶部筛选框(模糊查询/组合查询)
     * @param checkListVo
     * @return
     */
    @PostMapping("/filtrate")
    public PageInfo filtrate(@RequestBody CheckListVo checkListVo){
        //分页
        int pageNo = checkListVo.getPageNo();
        int pageSize = checkListVo.getPageSize();

        PageHelper.startPage(pageNo,pageSize);
        //修改检索条件
        List<Map<String, String>> search = checkListVo.getSearch1();
        List<Map<String,Object>> list = new ArrayList<>();
        if (search!=null&&search.size()>0){
            for (Map<String, String> stringMap : search) {
                Map<String,Object> map=new HashMap<>();
                map.put("op",stringMap.get("include"));
                map.put("precision",stringMap.get("precise"));
                HashMap<String, String> kv = new HashMap<>();
                kv.put("k",stringMap.get("value"));
                kv.put("v",stringMap.get("input"));
                map.put("kv",kv);
                list.add(map);
            }
            checkListVo.setSearch(list);
        }
        //判断左侧树具体为那个字段
        String id = checkListVo.getTerritory();
        if(id!=null&&id!="") {
            Territory territory = new Territory();
            territory.setId(id);
            List<Territory> territory1 = territoryService.getTerritory(territory);
            if (territory1.isEmpty()) {
                ProductLine productLine = new ProductLine();
                productLine.setId(id);
                List<ProductLine> productLine1 = productLineService.getProductLine(productLine);
                if (productLine1.isEmpty()) {
                    Product product = new Product();
                    product.setId(id);
                    List<Product> product1 = productService.getProduct(product);
                    if (!product1.isEmpty()) {
                        checkListVo.setTerritory(null);
                        checkListVo.setProduct(id);
                    }
                } else {
                    checkListVo.setTerritory(null);
                    checkListVo.setProductLine(id);
                }
            }
        }
        List<CheckList> infoList = checklistService.selectCheckList(checkListVo);
        PageInfo<CheckList> pageInfo = new PageInfo<>(infoList);

        return pageInfo;
    }

    /**
     * 解析word文档
     * @param filePath
     * @return
     */
    @GetMapping("/exportWord")
    public AjaxResult exportWord(@RequestParam("filePath") String filePath){
        String result = WordUtils.getTextFromWord(filePath);
        if(!result.isEmpty() || result.length() != 0){
            return AjaxResult.success(result);
        }
        return AjaxResult.error();
    }

    /**
     * 对比两个word文档
     * @param filea
     * @param fileb
     * @throws IOException
     */
    @GetMapping("/compare2file")
    public void compare2file(@RequestParam("filea") String filea,@RequestParam("fileb") String fileb) throws IOException {
        WordUtils.compareTwoFile(filea,fileb);
    }

    /**
     * 根据id查看详情(点击查看后浏览数+1)
     * @param id
     * @return
     */
    @Transactional
    @GetMapping("/getById")
    public AjaxResult getById(@RequestParam("id") String id){
        //获取对应checklist详情
        CheckList item = checklistService.getChecklistItemById(id);
        //获取应用场景
        List<String> applicationScenariosList = Arrays.asList(item.getApplicationScenarios().split(","));
        //获取关联典型问题
        List<String> typicalProblemList = Arrays.asList(item.getAssociatedTypical().split(","));
        //获取关联设计指导
        List<String> designGuideList = Arrays.asList(item.getAssociatedDesign().split(","));
        //新建返回结果List<Map>
        List<Map> resultList = new ArrayList<>();
        List<Map> resultList1 = new ArrayList<>();
        List<Map> resultList2 = new ArrayList<>();
        //返回应用场景
        for(String scene : applicationScenariosList){
            Map applicationScenariosNames = new HashMap();
            ApplySituation applySituation = applySituationService.getApplySituationById(scene);
            applicationScenariosNames.put("name",applySituation.getSceneName());
            resultList.add(applicationScenariosNames);
        }
        item.setApplicationScenariosNames(resultList);
        //返回关联典型问题
        for(String problem : typicalProblemList){
            Map typicalProblemMap = new HashMap();
            TypicalProblem typicalProblem = typicalProblemService.getById(problem);
            typicalProblemMap.put("name",typicalProblem.getName());
            resultList1.add(typicalProblemMap);
        }
        item.setTypicalProblems(resultList1);
        //返回关联设计指导
        for(String guide : designGuideList){
            Map designGuideMap = new HashMap();
            TypicalProblem typicalProblem = typicalProblemService.getById(guide);
            designGuideMap.put("name",typicalProblem.getName());
            resultList2.add(designGuideMap);
        }
        item.setDesignGuides(resultList2);

        //更新浏览数
        Integer browseTime = item.getBrowseTime();
        browseTime ++;
        item.setBrowseTime(browseTime);
        checklistService.updateChecklist(item);
        if(StringUtils.isNotNull(item)){
            return AjaxResult.success(item);
        }else{
            return AjaxResult.error("查询失败");
        }
    }

    /**
     * 根据知识编码进行版本对比
     * @param encoding
     * @return
     */
    @GetMapping("/getVersionsByEncoding")
    public AjaxResult getVersions(@RequestParam("encoding") String encoding){
        CheckList list = new CheckList();
        list.setEncoding(encoding);
        List<CheckList> checklists = checklistService.getList(list);
        if(checklists.size() != 0 && StringUtils.isNotNull(checklists)){
            return AjaxResult.success(checklists);
        }else{
            return AjaxResult.error("无更多版本记录");
        }
    }

    /**
     * 获取最新版本号
     * @param encoding
     * @return
     */
    @GetMapping("/getNewVersionNo")
    public AjaxResult getNewVersionVo(@RequestParam("encoding") String encoding){
        //拿取统一编码下的所有记录
        List<CheckList> checkList = checklistService.getChecklistItem(encoding);
        String str = "";
        //拿取时间最近的一条记录
        CheckList item = checkList.get(0);
        //获取其版本号
        String version = item.getVersion();
        //截取字符串
        str = version.substring(1,version.indexOf("."));
        //返回最新版本号
        int num = Integer.parseInt(str);
        num++;
        //拼接返回结果
        String result = "V" + num + ".0";
        return AjaxResult.success(result);
    }

    /**
     * 引用次数排行榜
     * @param checkList
     * @return
     */
    @GetMapping("/topQuote")
    public AjaxResult topQuote(CheckList checkList){
        List<CheckList> result = checklistService.topQuote(checkList);
        return AjaxResult.success(result);
    }

    @GetMapping("/getRetrieve")
    public AjaxResult getRetrieveInformation(){
        Map<String, Object> map = checklistService.getRetrieveInformation();
        if(StringUtils.isNotNull(map)){
            return AjaxResult.success(map);
        }else{
            return AjaxResult.error("查询失败");
        }
    }

}
